﻿using System;
using System.Data;

namespace SimpleService.ORM
{
    public class Select 
    {


        public PersistenceObject _table;

        public Select(PersistenceObject _table) { this._table = _table; }	

        private void GetDataRows(DataTable dt)
        {
            int i = 0;
            foreach (DataRow Row in dt.Rows)
            {
                foreach (DataColumn Columns in dt.Columns)
                {
                    _table.Rows.Set(i, Columns.ColumnName, Row[Columns.ColumnName].ToString().Trim());
                }
                i = i + 1;
            }
        }

        public void Execution()
        {
            
            string SQLstr = ORMConfig.select;
            SQLstr = SQLstr.Replace("__table__", _table._TableName);
            
            DataTable dt = SqlOperator.Table(SQLstr, _table._connection);
            _table.RowsCount = PersistenceUtility.RowsCount(dt); 
            _table.ColsCount = PersistenceUtility.ColumnsCount(dt); 
            _table.ColsName = PersistenceUtility.ColumnsName(dt); 
            _table.ColsType = PersistenceUtility.ColumnsType(dt); 

            if (dt.Rows.Count >= 1) { GetDataRows(dt); }
        }


        public void Execution(string keyin)
        {

            string SQLstr = "";

            if (keyin.ToLower().IndexOf("where ") > -1)
            {
                SQLstr = ORMConfig.select +keyin;
                SQLstr = SQLstr.Replace("__table__", _table._TableName);
            }
            else
            {
                SQLstr = ORMConfig.select + " " + ORMConfig.where;
                SQLstr = SQLstr.Replace("__table__", _table._TableName);
                SQLstr = SQLstr.Replace("__key__", _table.ColsName[0]); 
                SQLstr = SQLstr.Replace("__val__", _table.KeyType(keyin));
            }

            DataTable dt = SqlOperator.Table(SQLstr, _table._connection);
            _table.RowsCount = PersistenceUtility.RowsCount(dt); 
            _table.ColsCount = PersistenceUtility.ColumnsCount(dt); 
            _table.ColsName = PersistenceUtility.ColumnsName(dt); 
            _table.ColsType = PersistenceUtility.ColumnsType(dt); 

            if (dt.Rows.Count >= 1) { GetDataRows(dt); }
        } 
    }
}
